<template>
  <div class="smart-clip">
    <RouteTitle :isBack="true" />
    <a-spin tip="加载中..." :spinning="loading">
      <a-card >
        <div class="dubbing">
          <div class="dubbing-title">音色场景：</div>
          <div class="voice_type_box">
            <a-tabs v-model:activeKey="activeKey" @change="activeChange">
              <a-tab-pane v-for="tab in tabList" :key="tab.key" :tab="tab.value" />
            </a-tabs>

            <template v-if="voiceList.length">
              <div ref="voiceListContainer" :class="['voice_type_list', isExpanded ? 'expanded' : '']">
                <div class="n-tab-pane" v-for="(voice, index1) in voiceList" :key="voice.gender_type">
                  <div class="group-name">{{ voice.gender_title }}：</div>
                  <a-row style="flex: 1" :wrap="true">
                    
                    <a-col v-for="(item, index2) in voice.item" :key="item.id" @click="voiceClick(item)">
                      <div class="group-box" :class="
                          timbreId == item.timbre_id && voiceId == item.id
                            ? 'group-border'
                            : ''
                        ">
                        <div class="right-badge" v-if="item.quality == 2">
                          <cu-icon type="icon-zuanshihuiyuan" style="font-size: 18px" />
                          精品
                        </div>
                        <div class="avatar">
                          <a-avatar :src="item.img" />
  
                          <div v-if="item.loading" class="spain_spain">
                            <!-- style="position: absolute; left: 5px; top: 8px" -->
                            <a-spin />
                          </div>
                          <div class="mask" @click="playbackClick(item, index1, index2)">
                            <cu-icon class="icon" :type="
                                !item.isPlay ? 'icon-bofang1' : 'icon-zanting'
                              " />
                          </div>
                        </div>
                        <div>
                          <div>{{ item.name }}</div>
                          <div>{{ item.human_style }}</div>
                        </div>
                      </div>
                    </a-col>
                  </a-row>
                </div>
              </div>

             <div class="see_more" @click="changeFn" v-if="!ismore">
                <span v-if="!isExpanded">展开更多</span>
                <span v-else>收起更多</span>
                <caret-down-outlined v-if="!isExpanded" />
                <caret-up-outlined v-else />
             </div>
            </template>

            <template v-else>
              <a-col :span="24" style="
                  display: flex;
                  justify-content: center;
                  align-items: center;
                  height: 200px;
                ">
                <a-empty :image="Empty.PRESENTED_IMAGE_SIMPLE" />
              </a-col>
            </template>
          </div>
        </div>
        <div class="voice" v-if="
            voiceList.length &&
            activeKey != 'customized_vol' &&
            activeKey != 'recommend'
          ">
          <a-row align="middle" :gutter="[0, 16]" justify="space-between" style="width: 100%">
            <a-col style="display: flex; align-items: center">
              <div class="voice-item">
                <div class="copywriting-title">语气：</div>
                <a-select v-model:value="emotion_category" placeholder="请选择" style="width: 160px; margin-right: 30px"
                  :disabled="toneDisabled">
                  <a-select-option v-for="item in toneList" :value="item.key" :key="item.key">
                    {{ item.value }}
                  </a-select-option>
                </a-select>
              </div>
            </a-col>
            <a-col style="display: flex; align-items: center">
              语速：<a-slider v-model:value="speed" :max="voiceConfige.speed.max" :min="voiceConfige.speed.min"
                :step="voiceConfige.speed.step" />
            </a-col>
            <a-col style="display: flex; align-items: center">
              情感：
              <a-slider v-model:value="emotion_intensity" :max="voiceConfige.emotion_intensity.max"
                :min="voiceConfige.emotion_intensity.min" :step="voiceConfige.emotion_intensity.step" />
            </a-col>

            <a-col style="display: flex; align-items: center">
              音量：<a-slider v-model:value="volume" :max="voiceConfige.volume.max" :min="voiceConfige.volume.min"
                :step="voiceConfige.volume.step" />
            </a-col>
          </a-row>
        </div>

        <!-- 音色为推荐的时候, 只显示语速 -->
        <div class="voice" v-else-if="activeKey == 'recommend'">
          <a-row align="middle" :gutter="[0, 16]" justify="space-between" style="width: 100%">
            <a-col style="display: flex; align-items: center">
              语速：<a-slider v-model:value="speed" :max="volcengine_config.speed.max" :min="volcengine_config.speed.min"
                :step="volcengine_config.speed.step" />
            </a-col>
          </a-row>
        </div>

        <!-- 音色为声音克隆的时候, 只显示语速 -->
        <div class="voice" v-else-if="activeKey == 'customized_vol'">
          <a-row align="middle" :gutter="[0, 16]" justify="space-between" style="width: 100%">
            <a-col style="display: flex; align-items: center">
              语速：<a-slider v-model:value="speed" :max="speed_ratio.speed.max" :min="speed_ratio.speed.min"
                :step="speed_ratio.speed.step" />
            </a-col>
          </a-row>
        </div>
      </a-card>
      <a-card v-if="voiceList.length">
      <a-tabs v-model:activeKey="Text_activeKey" @change="Text_story_Change">
        <a-tab-pane key="1" tab="文字转语音">
        <div class="copywriting" v-for="(item, index) in textList" :key="index">
          <div class="copywriting-music">
            <div class="copywritingmusic-title">
              <div class="one">
                文案 <span v-if="textList.length > 1">{{ index + 1 }}</span> ：
              </div>
              <div class="two">
                ( {{ item.music_name }} - {{ item.music_desc }} )
              </div>
            </div>
          </div>

          <div class="copywriting-content">
            <div class="textarea-wrapper">
              <!-- <a-textarea :bordered="false" v-model:value="item.content" :autoSize="{ minRows: 6 }" :maxlength="max_text_length"
                show-count @change="textareaChange($event, index)" style="background-color: rgb(246, 246, 246);border-radius: 6px;"></a-textarea> -->
              <Editor :ref="(el) => editorRef[index] = el" :hiddenSSML="999" :maxlength="2000" @textChagne="textareaChange(index)" />
              <div class="operation">
                <div class="flex align-center">
                  <a-col class="auto-box">
                    <audio-player v-if="item.isResultUrl && textradio" class="audio-box" :fileurl="item.isResultUrl"
                      :playNum="item.playNum" :index="index" @audioStatus="audioStatus($event, index)"
                      @setAudio="setAudio(index)" />
                  </a-col>
                  <a-space>
                    <a-button v-if="!item.isResultUrl" type="primary" @click="playAutoClick(item, index)">
                      点击生成音频
                    </a-button>
                    <a-button v-if="item.isResultUrl" type="primary" @click="playAutoClick(item, index)">
                      {{
                      !item.isPlay && item.isResultUrl ? "暂停" : "播放"
                      }}</a-button>
                    <a-button type="link"  class="import_meatiner_btn"
                      @click="openCopyLibraryModal(item, index)">文案库导入</a-button>


                      <a-button type="link" class="import_meatiner_btn"
                      @click="aIRewriting(
                        {
                          ...item,
                          clickType: 'AIRewriting',
                          index,
                          labelType: 'desc',
                        }
                      )">AI改写</a-button>
                      <a-button type="link"  class="import_meatiner_btn"
                      @click="aIRewriting(
                        {
                          ...item,
                          clickType: 'AIExpand',
                          index,
                          labelType: 'desc',
                        }
                      )">AI扩写</a-button>
                    <a-button v-if="item.isResultUrl" type="primary" @click="saveMaterials(item)">保存到素材</a-button>
                    <a-button v-if="item.isResultUrl" type="primary" ghost :loading="item.soundLoading"
                      @click="downloadSound(item)">下载声音</a-button>
                    <delete-outlined v-if="textList.length > 1" class="operation-btn" @click="delTxt(index)" />
                  </a-space>
                </div>
              </div>
              <div class="mask-text" v-if="item.indicator">
                <a-spin :indicator="indicator" />
                <div class="mask-box">音频合成中，请稍后...</div>
              </div>
            </div>
          </div>
        </div>
        <div class="add-btn" @click="addTxt">
          <a-button type="dashed" style="width: 100%"><plus-outlined />添加一段文案</a-button>
        </div>
        </a-tab-pane>

        <a-tab-pane key="2" tab="小说转语音">
        <div class="copywriting" v-for="(item, index) in storyList" :key="index">
          <div class="copywriting-music">
            <div class="copywritingmusic-title"  style="justify-content: space-between;">
              <div class="left">
              <div class="one">
                文案 <span v-if="storyList.length > 1">{{ index + 1 }}</span> ：
              </div>
              <div class="two">
                ( {{ item.music_name }} - {{ item.music_desc }} )
              </div>

              </div>
              <div class="right" v-if="consumes > 0">
                小说转语音将按照每100字扣除{{consumes}}{{unit}}{{unit_name}}进行计费(不足100字按照100字计算)
              </div>
             
            </div>
          </div>

          <div class="copywriting-content">
            <div class="textarea-wrapper">
              <Editor :ref="(el) => editorRef[index] = el" :hiddenSSML="999" :maxlength="2000"  @textChagne="textareaChange(index)" />
              <div class="operation">
                <div class="flex align-center">
                  <a-col class="auto-box">
                    <audio-player v-if="item.isResultUrl && storyadio" class="audio-box" :fileurl="item.isResultUrl"
                      :playNum="item.playNum" :index="index" @audioStatus="audioStatus($event, index)"
                      @setAudio="setAudio(index)" />
                  </a-col>
                  <a-space>
                    <a-button v-if="!item.isResultUrl" type="primary" @click="playAutoClick(item, index)">
                      点击生成音频
                    </a-button>
                    <a-button v-if="item.isResultUrl" type="primary" @click="playAutoClick(item, index)">
                      {{
                      !item.isPlay && item.isResultUrl ? "暂停" : "播放"
                      }}</a-button>
                    <a-button type="link" class="import_meatiner_btn"
                      @click="openCopyLibraryModal(item, index)">文案库导入</a-button>
                      <a-button type="link" class="import_meatiner_btn"
                      @click="aIRewriting(
                        {
                          ...item,
                          clickType: 'AIRewriting',
                          index,
                          labelType: 'desc',
                          type:'storyList'
                        }
                      )">AI改写</a-button>
                      <a-button type="link"  class="import_meatiner_btn"
                      @click="aIRewriting(
                        {
                          ...item,
                          clickType: 'AIExpand',
                          index,
                          labelType: 'desc',
                          type:'storyList'
                        }
                      )">AI扩写</a-button>
                    <a-button v-if="item.isResultUrl" type="primary" @click="saveMaterials(item)">保存到素材</a-button>
                    <a-button v-if="item.isResultUrl" type="primary" ghost :loading="item.soundLoading"
                      @click="downloadSound(item)">下载声音</a-button>
                    <delete-outlined v-if="storyList.length > 1" class="operation-btn" @click="delTxt(index)" />
                  </a-space>
                </div>
              </div>
              <div class="mask-text" v-if="item.indicator">
                <a-spin :indicator="indicator" />
                <div class="mask-box">音频合成中，请稍后...</div>
              </div>
            </div>
          </div>
        </div>
        <div class="add-btn" @click="addTxt">
          <a-button type="dashed" style="width: 100%"><plus-outlined />添加一段文案</a-button>
        </div>

        </a-tab-pane>
      </a-tabs>


       
      </a-card>
    </a-spin>

    <!-- 保存到素材弹框 -->
    <MaterialsModule :visible="visibleMaterials" material_type="audio" :data="materialData" @onCancel="visibleMaterials = false"
      @onSuccess="visibleMaterials = false" />
  </div>
  <!-- 素材库弹窗 -->
  <ChooseMaterial :isClip="true" material_type="text" :multiple="true" :visible="materiallibraryShow"
    @close="closeChooseMaterial($event, 'material_type')" />
  <!-- 文案库 -->
  <CopyLibraryModal ref="copyLibraryModal" @importSuccess="audioLItemImportSuccess" />

  <!-- <notTextSpeech :useNum="currentNum" :consumes="consumes" :name_unit="name_unit" :unit="unit" @handleOk="handleOk"
    ref="notVoiceNumDialogRef">
  </notTextSpeech> -->

  <!-- 充值弹窗 -->
  <vipModal ref="vipModalRef" :visible="vipVisible" @close="vipVisible = false"></vipModal>

  
    <!-- 文案仿写组件 -->
    <TextImitationDialog ref="TextImitationDialogRef" :isComponents="true" :isonece="true" @getTextArr="getTextArr">
    </TextImitationDialog>

</template>

<script>
import {
  defineComponent,
  reactive,
  toRefs,
  nextTick,
  ref,
  h,
  onMounted,
  onUnmounted,
  watch,
  computed
} from "vue";

// 充值弹窗
import vipModal from '@/socialMedia/Vip/vipModal.vue'
const vipModalRef = ref(null)
import {
  PlusOutlined,
  DeleteOutlined,
  CaretRightOutlined,
  PauseCircleFilled,
  LoadingOutlined,
  CaretDownOutlined,
  CaretUpOutlined
} from "@ant-design/icons-vue";
import CreateFixed from "../components/CreateFixed/index.vue";
import request from "../../../common/utils/request";
import utils from "../../../common/utils/utils";
import { message, notification, Empty } from "ant-design-vue";
import MaterialsModule from "../components/MaterialsModule/materialLibraryModal.vue";
// import notTextSpeech from "@/views/shotstack/CreationCenter/components/notTextSpeech.vue";
import dayjs from "dayjs";
import AudioPlayer from "../components/AudioPlayer/index.vue";
import { useRoute, useRouter } from "vue-router";
import store from "@/store/index.js";
import { saveAs } from "file-saver";
// 文案库组件
import CopyLibraryModal from "@/components/AddTextModal/CopyLibraryModal.vue";
// 素材库
import ChooseMaterial from "@/views/shotstack/EditingCenter/modules/bottomSet/components/chooseMaterial.vue";
// 文案仿写
import TextImitationDialog from "@/views/shotstack/components/TextImitationDialog/index.vue";
// 最大字数限制
import {
  max_text_length
} from "@/common/utils/richTextProcessing.js";

import Editor from '../digitalHuman/AIdigitalHumanCreatVideo/Components/editor/index.vue'
                

export default defineComponent({
  name: "TextToSpeech",
  components: {
    DeleteOutlined,
    PlusOutlined,
    CaretRightOutlined,
    PauseCircleFilled,
    MaterialsModule,
    AudioPlayer,
    vipModal,
    ChooseMaterial,
    CopyLibraryModal,
    CaretDownOutlined,
    CaretUpOutlined,
    TextImitationDialog,
    // notTextSpeech,
    Editor
  },
  setup() {

    const appName =ref('')


  
    const notVoiceNumDialogRef = ref(null);
    const state = reactive({
      ismore: true,
      textradio : true,
      storyadio : true,
      // 文案
      textList: [
        {
          content: '',
          isPlay: false,
          indicator: false,
          isResultUrl: "",
          playNum: 0,
          soundLoading: false,
          music_name: "",
          music_desc: "",
          timbreId: "",
        },
      ],
      storyList: [
        {
          content: '',
          isPlay: false,
          indicator: false,
          isResultUrl: "",
          playNum: 0,
          soundLoading: false,
          music_name: "",
          music_desc: "",
          timbreId: "",
        },
      ],
      // 语气
      emotion_category: "",
      toneList: [],
      toneDisabled: true,
      // 语速
      speed: 0,
      // 音频情感程度
      emotion_intensity: 100,
      // 音量
      volume: 6,
      voiceConfige: {
        speed: {
          max: 2,
          min: -2,
          step: 1,
          default: 1,
        },
        emotion_intensity: {
          max: 200,
          min: 50,
          step: 1,
        },
        volume: {
          max: 11,
          min: 1,
          step: 1,
        },
      },
      // 推荐专属的配置
      volcengine_config: {
        speed: {
          max: 2,
          min: -2,
          step: 1,
          default: 1,
        },
      },
      // 克隆专属的配置
      speed_ratio: {
        speed: {
          max: 3,
          min: 0.2,
          step: 0.1,
          default: 1,
        },
      },
      volume_type: "",
      loading: false,
      activeKey: "recommend",
      tabList: [],
      columns: [
        { title: "序号", dataIndex: "id", key: "id" },
        { title: "状态", dataIndex: "id", key: "id" },
        { title: "时间信息", dataIndex: "id", key: "id" },
        { title: "操作", dataIndex: "id", key: "id" },
      ],
      voiceList: [],
      voiceData: {},
      timbreId: null,
      voiceId: null,

      visibleMaterials: false,
      materialData: {},
      autoIsPlay: false,

      audioPlayer: null,
      materiallibraryShow: false, //控制素材库弹框显示
      isExpanded:false,
      category: "",
      Text_activeKey: "1",
      unit: "",
      unit_name: "",
      consumes: "",
      voiceListContainer: null,
      TextImitationDialogRef: null,

      ssml:'',
      text:''
    });

    const editorRef=ref([])

    onMounted(()=>{
      store.dispatch("getAiConfig").then((aiConfig) => {
        appName.value = aiConfig.site_name
        state.textList[0].content = `欢迎使用${appName.value}视频文字转语音工具`
        state.storyList[0].content = `欢迎使用${appName.value}视频文字转语音工具`
        nextTick(()=>{
          setTimeout(() => {
            editorRef.value[0].setContent( `欢迎使用${appName.value}视频文字转语音工具`)
          }, 500);
        })
      })
    })

    const vipVisible = ref(false)

    const route = useRoute();
    const router = useRouter();

    const truncateText = (text, length) => {
      let result = []; // 存放结果的数组
      while (text.length > length) {
        result.push(text.substring(0, length)); // 从原始文本中取出指定长度的子串并添加到结果数组中
        text = text.slice(length); // 去除已经处理过的部分
      }
      if (text !== "") {
        result.push(text); // 如果还有未处理完的内容，则直接添加到结果数组中
      }
      return result;
    };

    if (route.query?.contents) {
      if (
        route.query?.contents?.length &&
        route.query?.contents?.length >= 500
      ) {
        let contents = utils.removeEmoji(route.query?.contents);
        let arr = truncateText(contents, 500);

        if (state.Text_activeKey == "1") {
        state.textList = [];
        arr.map((item) => {
          state.textList.push({
            content: item,
            isPlay: false,
            indicator: false,
            isResultUrl: "",
            playNum: 0,
            soundLoading: false,
          });
        });
        } else {
           state.storyList = [];
        arr.map((item) => {
          state.storyList.push({
            content: item,
            isPlay: false,
            indicator: false,
            isResultUrl: "",
            playNum: 0,
            soundLoading: false,
          });
        });
        }
      } else {
        let contents = utils.removeEmoji(route.query?.contents);
        if (state.Text_activeKey == "1") {
          state.textList[0].content = contents;
        } else {
          state.storyList[0].content = contents;
          
         }
      }
    }

    const getList = () => {
      state.loading = true;
      request
        .get("/work_ai", "/user/shotstack/voice/category")
        .then((res) => {
          state.tabList = res.result;
          state.activeKey = res.result[0].key;
          state.loading = false;
          getVoiceList();
          getDefaultVoiceData();
        })
        .catch(() => {
          state.loading = false;
        });
    };

    const getVoiceList = () => {
      state.loading = true;
      request
        .get("/work_ai", "/user/shotstack/voice/list", {
          category: state.activeKey,
        })
        .then((res) => {
          state.ismore = false
          state.isExpanded = false
          if (res.result.length) {
            state.voiceData = res.result[0].item[0];
            // timbreId有可能重复, 新增一个voiceid字段
            state.timbreId = res.result[0].item[0].timbre_id;
            state.voiceId = res.result[0].item[0].id;

            if (!state.textList[0].isResultUrl && !state.textList[0].indicator) {
               state.textList[0].music_name = res.result[0].item[0].name;
            state.textList[0].music_desc = res.result[0].item[0].human_style;
            state.textList[0].timbreId = res.result[0].item[0].timbre_id;
            }

            if (!state.storyList[0].isResultUrl && !state.textList[0].indicator) {
               state.storyList[0].music_name = res.result[0].item[0].name;
            state.storyList[0].music_desc = res.result[0].item[0].human_style;
            state.storyList[0].timbreId = res.result[0].item[0].timbre_id;
             }
           
           

            state.toneList = res.result[0].item[0].emotion_style;
            // 切换之后, 更新分组和音色id
            state.category = state.activeKey;
            res.result.forEach((item) => {
              item.item.forEach((sub) => {
                sub.isPlay = false;
              });
            });

            state.voiceList = res.result.map((v1) => {
              v1.item = v1.item.map((item) => ({
                ...item,
                loading: false,
              }));
              return v1;
            });
            // state.voiceList[0].item = [...state.voiceList[0].item, { ...state.voiceList[0].item[0], id: 'customized_vol_26' }]
            state.emotion_category = res.result[0].item[0].emotion_style[0].key;
            if (res.result[0].item[0].emotion_style.length == 1) {
              state.toneDisabled = true;
              state.loading = false;
          setTimeout(() => {
            handleScroll()
          }, 10)
              return;
            }
            state.toneDisabled = false;

            let num = 0
            state.voiceList.forEach((v1, index) => {
              num += v1.item.length;
            })

          } else {
            state.voiceList = [];
          }
          state.loading = false;
          setTimeout(() => {
            handleScroll()
          }, 10)


        });
    };

    const voiceClick = (data) => {
      let is_push = false;
      let isedit = false;
      if (state.Text_activeKey == "1") {
      state.textList.forEach((item) => {
        if (item.isResultUrl == "" && !item.indicator) {
          item.timbreId = data.timbre_id;
          item.music_name = data.name;
          item.music_desc = data.human_style;
          isedit = true;
          is_push = false;
        } else {
          is_push = true;
        }
      });
      } else {
      state.storyList.forEach((item) => {
        if (item.isResultUrl == "" && !item.indicator) {
          item.timbreId = data.timbre_id;
          item.music_name = data.name;
          item.music_desc = data.human_style;
          isedit = true;
          is_push = false;
        } else {
          is_push = true;
        }
      });
      }
 


      if (is_push && !isedit) {
        if (state.Text_activeKey == "1") {
          state.textList.push({
          content: `欢迎使用${appName.value}视频文字转语音工具`,
          isPlay: false,
          indicator: false,
          isResultUrl: "",
          playNum: 0,
          soundLoading: false,
          music_name: data.name,
          music_desc: data.human_style,
          timbreId: data.timbre_id,
        });
        } else {
           state.storyList.push({
          content: `欢迎使用${appName.value}视频文字转语音工具`,
          isPlay: false,
          indicator: false,
          isResultUrl: "",
          playNum: 0,
          soundLoading: false,
          music_name: data.name,
          music_desc: data.human_style,
          timbreId: data.timbre_id,
        });
         }

      }
      state.voiceData = data;
      state.timbreId = data.timbre_id;
      state.voiceId = data.id;
      state.emotion_category = data.emotion_style[0].key;
      state.toneList = data.emotion_style;
      state.category = data.category;
      if (data.emotion_style.length == 1) {
        state.toneDisabled = true;
        return;
      }
      state.toneDisabled = false;
    };

    getList();

    // 切换之前备份的语速
    const cloneDefault = ref({
      recommendSpeed: null,
      atherSpeed: null,
      clone_speend: null,
      lastKey:''
    });

    const activeChange = async () => {
      // 改变时 赋值不同的默认值
      if (cloneDefault.value.lastKey == 'recommend') {
        cloneDefault.value.recommendSpeed = JSON.parse(
            JSON.stringify(state.speed)
          );
      } else if (cloneDefault.value.lastKey == 'customized_vol') {
        cloneDefault.value.clone_speend = JSON.parse(
            JSON.stringify(state.speed)
          );
      } else {
        cloneDefault.value.atherSpeed = JSON.parse(
            JSON.stringify(state.speed)
          );
      }
      if (state.volume_type == "aliyun") {
        if (state.activeKey == "recommend") {
          state.speed =
            cloneDefault.value.recommendSpeed ||
            state.volcengine_config.speed.default;
        } else if (state.activeKey == "customized_vol") {
          state.speed =
            cloneDefault.value.clone_speend ||
            state.speed_ratio.speed.default;
        } else {
          state.speed =
            cloneDefault.value.atherSpeed || state.voiceConfige.speed.default;
        }
      }
      cloneDefault.value.lastKey = state.activeKey
      await getVoiceList();


      console.log(state.voiceListContainer,  '看看挂载的是啥12313123131232131');
      // state.voiceListContainer.addEventListener('scroll', handleScroll());
    };

    // 播放/暂停
    const playbackClick = (data, index1, index2) => {
      data.isPlay = !data.isPlay;
      state.voiceList[index1].item[index2].loading = true;

      if (data.isPlay) {
        if (state.audioPlayer) {
          state.audioPlayer.pause(); // 暂停当前播放的音频
          state.audioPlayer.src = "";
        }
        state.audioPlayer = new Audio(data.voice_url); // 播放下一个音频文件

        state.audioPlayer.addEventListener("canplaythrough", () => {
          state.voiceList[index1].item[index2].loading = false; // 关闭加载状态
        });

        state.audioPlayer.play(); // 开始播放音频
      } else {
        state.audioPlayer.src = "";
        state.audioPlayer.pause();
      }
      state.voiceList.forEach((voice) => {
        if (voice.item) {
          voice.item.forEach((item) => {
            if (item.id !== data.id) {
              item.isPlay = false;
            }
          });
        }
      });
      if (state.audioPlayer) {
        state.audioPlayer.addEventListener("ended", function () {
          // 这里写入结束回调函数的代码
          console.log("结束语音");

          state.voiceList.forEach((voice) => {
            if (voice.item) {
              voice.item.forEach((item) => {
                if (item.id == data.id) {
                  item.isPlay = false;
                }
              });
            }
          });
        });
      }
    };

    // 文案添加
    const addTxt = () => {
      if (store.getters.isVersionExpired) {
        notification.warn({ message: "您的套餐已到期", duration: 2 });
        vipVisible.value = true;
      } else {
        let name;
        let desc;
        state.voiceList.forEach((v1) => {
          v1.item.forEach((v2) => {
            if (String(state.timbreId) === String(v2.timbre_id)) {
              name = v2.name;
              desc = v2.human_style;
            }
          });
        });
        if (state.Text_activeKey == "1") {
          state.textList.push({
            content: `欢迎使用${appName.value}视频文字转语音工具`,
            isPlay: false,
            indicator: false,
            isResultUrl: "",
            playNum: 0,
            soundLoading: false,
            music_name: name,
            music_desc: desc,
            timbreId: state.timbreId,
          });

          let listNum =[]
          state.textList.forEach((item, index) => {
            listNum.push(index)
            console.log(listNum,'listNum');
            setTimeout(() => {
              editorRef.value[listNum[listNum.length-1]].setContent( `欢迎使用${appName.value}视频文字转语音工具`)
            }, 500);
          });
        } else {
           state.storyList.push({
            content: `欢迎使用${appName.value}视频文字转语音工具`,
            isPlay: false,
            indicator: false,
            isResultUrl: "",
            playNum: 0,
            soundLoading: false,
            music_name: name,
            music_desc: desc,
            timbreId: state.timbreId,
           });
           let listNum =[]
          state.storyList.forEach((item, index) => {
            listNum.push(index)
            console.log(listNum,'listNum');
            setTimeout(() => {
              editorRef.value[listNum[listNum.length-1]].setContent( `欢迎使用${appName.value}视频文字转语音工具`)
            }, 500);
          });
        }

     

      }
    };
    const delTxt = (index) => {
      if (state.Text_activeKey == "1") {
        state.textList.splice(index, 1);
      } else {
        state.storyList.splice(index, 1);
       }
    };
    // 播放文案
    const playAutoClick = async (data, index) => {
      if (store.getters.isVersionExpired) {
        notification.warn({ message: "您的套餐已到期", duration: 2 });
        vipVisible.value = true;
        return
      } 

        if (data.isResultUrl) {
          data.isPlay = !data.isPlay;
          if (state.Text_activeKey == "1") {
          data.content = 
          state.textList.forEach((item, textIndex) => {
            if (textIndex == index) {
              item.isPlay = data.isPlay;
              item.playNum++;
            }
          });
          } else {
            state.storyList.forEach((item, textIndex) => {
            if (textIndex == index) {
              item.isPlay = data.isPlay;
              item.playNum++;
            }
          });
          }

          return;
      }

    const textData = await synchronizeText(index)
        if (!textData) {
          message.warn("请输入文案");
          return;
      }


      if (state.Text_activeKey == "1") {
          try {
            const res = await utils.textConfigGet({
              number: textData.textData.text.length
            })
            // 查询积分, 积分不足则走不到这一步
            // 获取积分消耗提示内容
            const content = utils.useText(res)
            try {
              // 确认消耗
              await utils.kd({ content,res })
            } catch (error) {
              return
            }
          } catch (error) {
            // 打开充值, 接着打开点数购买
            vipVisible.value = true
            vipModalRef.value && vipModalRef.value.openBuyVisible()
            return
          }
          data.content = textData.textData.ssml
          handleOk(data, index)
        
      } else {
          console.log(textData.textData.text.length,'textData.textData.text.length');
          try {
            const res = await utils.storyConfigGet({
              number: Math.ceil(textData.textData.text.length / 100)
            })
            const content = utils.useText(res)
            try {
              // 确认消耗
              await utils.kd({ content,res })
            } catch (error) {
              return
            }
          } catch (error) {
            // 打开充值, 接着打开点数购买
            vipVisible.value = true
            vipModalRef.value && vipModalRef.value.openBuyVisible()
            return
          }
          data.content = textData.textData.ssml
          handleOk(data, index)
      }
    };

    const handleOk = (data, index) => {
      let params = {
        text: data.content,
        speed: state.speed,
        timbre_id: state.Text_activeKey == "1" 
  ? state.textList[index].timbreId 
  : state.storyList[index].timbreId,
        volume: state.volume - 1,
        emotion_category: state.emotion_category,
        emotion_intensity: state.emotion_intensity,
        id: state.voiceId,
        category: state.category,
      };

      data.indicator = true;
      if (state.Text_activeKey == "1") {
      request
        .post("/work_ai", "/user/shotstack/textToVoice", params)
        .then((res) => {
          let tiem = setInterval(() => {
            request
              .get("/work_ai", "/user/shotstack/getVoice", {
                task_id: res.result.task_id,
                request_id: res.result.request_id || "",
              })
              .then((task) => {
                if (task.result?.Data?.ResultUrl) {
                  data.isResultUrl = task.result.Data.ResultUrl;
                  data.indicator = false;
                  data.isPlay = false;
                  data.voiceName = res.result.voice_name;
                  clearInterval(tiem);
                }
              });
          }, 1500);
        });
      } else {
      request
        .post("/work_ai", "/user/shotstack/storyToVoice", params)
        .then((res) => {
          let tiem = setInterval(() => {
            request
              .get("/work_ai", "/user/shotstack/getVoice", {
                task_id: res.result.task_id,
                request_id: res.result.request_id || "",
              })
              .then((task) => {
                if (task.result?.Data?.ResultUrl) {
                  data.isResultUrl = task.result.Data.ResultUrl;
                  data.indicator = false;
                  data.isPlay = false;
                  data.voiceName = res.result.voice_name;
                  clearInterval(tiem);
                }
              });
          }, 1500);
        });
      }


    };

    // 监听语音播放结束
    const audioStatus = (status, index) => {
      if (status) {
        if (state.Text_activeKey == "1") {
            state.textList.forEach((item, textIndex) => {
          if (textIndex == index) {
            item.isPlay = !item.isPlay;
          }
        });
        } else {
          state.storyList.forEach((item, textIndex) => {
          if (textIndex == index) {
            item.isPlay = !item.isPlay;
          }
        });
         }


      }
    };

    const setAudio = (index) => {
      if (state.Text_activeKey == "1") {
         state.textList.forEach((item, textIndex) => {
        if (textIndex == index) {
          item.isPlay = false;
        }
      });
      } else {
          state.storyList.forEach((item, textIndex) => {
        if (textIndex == index) {
          item.isPlay = false;
        }
      });
       }
     
    };

    // 监听输入框变化
    const textareaChange = (index) => {
      if (state.Text_activeKey == "1") {
         state.textList.forEach((item, textIndex) => {
        if (textIndex == index) {
          item.isResultUrl = "";
        }
      });
      } else {
          state.storyList.forEach((item, textIndex) => {
        if (textIndex == index) {
          item.isResultUrl = "";
        }
      });
       }
     
    };
    // 打开素材库弹窗
    const currentImportIndex = ref(null); //当前导入文案的索引
    let copyLibraryModal = ref(null); //素材库导入组件实例
    // 文案库导入
    const openCopyLibraryModal = (item, index) => {
      currentImportIndex.value = index;
      copyLibraryModal.value && copyLibraryModal.value.showModal();
    };

    // AI改写
    const aIRewriting = async (item, index) => {
      const textData = await synchronizeText(item.index)
    const text = textData?.textData?.text??''
       if (item.labelType == "desc" && text.trim().length <= 0) {
        message.error("请输入内容")
        return
      }
      console.log(item.index,'index');
      try {
        // 查看用户的点数是否足够消耗
        await utils.aiTextGet()
        try {
          // 消耗规则
          const rule = await utils.consumptionPointRule()
          // 获取提示
          const content = utils.ruleTips({ res: rule, key: "ai_text_point" })
          // 弹出提示
          await utils.md({ content })
          // 弹窗确认消耗
        } catch (error) {
          return
        }
      } catch (error) {
        // 打开充值, 接着打开点数购买
        vipVisible.value = true
        vipModalRef.value && vipModalRef.value.openBuyVisible()
        return
      }

        const params = {
          is_text_rewrite: item.clickType == "AIRewriting" ? 1 : 0, // 0-扩写AIExpand 1-改写AIRewriting
          ai_keyword_id: item.ai_keyword_id,
          ai_keyword_group_id: item.ai_keyword_group_id,
          content: textData.textData.text,
          ai_type: item.labelType, //扩写或者改写类型 desc-描述的扩写或者改写 title-标题的扩写或者改写
          platform:''
        };
        state.loading = true;
        try {
          const successRes = await request.post(
            "work_ai",
            "/user/filmrelease/ai/generate_title",
            params
          );
          if (!successRes || !successRes.result) {
            state.loading = false;
            return message.error("AI扩写生成失败，状态id丢失");
          }

          const timerId = setInterval(async () => {
            try {
              const statusRes = await request.get(
                "/work_ai",
                "/user/filmrelease/ai/generate_title/status",
                { task_id: successRes.result }
              );
              if (
                statusRes.result.status === "success" ||
                statusRes.result.status === "error"
              ) {
                if (statusRes.result.data.length) {
                  if(item.type=='storyList'){
                    state.storyList.forEach((textItem,index)=>{
                      if(item.index == index){
                        textItem.content = statusRes.result.data[0];
                      }
                    })
                  }else{
                    state.textList.forEach((textItem,index)=>{
                      if(item.index == index){
                        textItem.content = statusRes.result.data[0];
                      }
                    })
                  }

                  textareaChange(item.index)
                  editorRef.value[item.index].setContent(statusRes.result.data[0])
                } else {
                  message.error("AI生成内容失败");
                }
                clearInterval(timerId);
                state.loading = false;
              }
            } catch (statusErr) {
              console.log(statusErr);
              state.loading = false;
              clearInterval(timerId);
            }
          }, 1000);
        } catch (errorRes) {
          console.log(errorRes);
          state.loading = false;
        }
    }

    // 文案仿写
    // const copyImitation=()=>{
    //   state.TextImitationDialogRef.showModal();
    // }

    const getTextArr=(list)=>{
      console.log(list,'list');
    }

    // 文案库导入成功回调
    const audioLItemImportSuccess = (data) => {

      console.log(data,'data的数据');
      const text = data[0].material_content;

      if (text !== "") {
        if (text > max_text_length) {
          message.error(`超出文案最大长度${max_text_length}限制`);
          return;
        }
        if (state.Text_activeKey == "1") {
          state.textList[currentImportIndex.value].content = text
        } else {
          state.storyList[currentImportIndex.value].content = text
        }
        console.log(editorRef.value,'editorRef.value');
        
        editorRef.value[currentImportIndex.value]?.setContent(text)
      }
      copyLibraryModal.value && copyLibraryModal.value.closeModal();
    };
    // 保存到素材
    const saveMaterials = (data) => {
      state.materialData.autoName = `${data.voiceName}_${dayjs().format(
        "YYYYMMDDHHmmss"
      )}.mp3`;
      state.materialData.material_url = data.isResultUrl;
      state.visibleMaterials = true;
    };

    // 下载声音
    const downloadSound = (data) => {
      data.soundLoading = true;
      try {
        let saveName = state.voiceData.name;
        const hide = message.loading("下载中..", 0);
        if (!saveName) {
          const lastSlashIndex = data?.isResultUrl.lastIndexOf("/");
          saveName = data?.isResultUrl.slice(lastSlashIndex + 1);
        }
        saveAs(data?.isResultUrl, saveName);

        data.soundLoading = false;
        setTimeout(hide, 0);
      } catch (error) {
        data.soundLoading = false;
        message.destroy();
        nextTick(() => {
          message.error("下载失败");
        });
        return;
      }
    };

    const indicator = h(LoadingOutlined, {
      style: {
        fontSize: "30px",
      },
      spin: true,
    });

    // 获取音频基础配置, 如果是阿里云 则替换初始值
    const getDefaultVoiceData = async () => {
      const res = await request.get(
        "/work_ai",
        "/user/shotstack/voice/config/get"
      );
      console.log(res, "获取音频配置");
      state.volume_type = res?.voice_config?.volume_type;
      if (res?.voice_config?.volume_type == "aliyun") {
        // 判断当前的 activeKey, 赋值不同的 速度
        if (state.activeKey == "recommend") {
          state.speed = res.volcengine_config.speed.default;
        } else {
          state.speed = res.voice_config.speed.default;
        }
        state.volume = res.voice_config.volume.default;
        state.emotion_intensity = res.voice_config.intensity.default;
        state.voiceConfige.speed = {
          max: res.voice_config.speed.max,
          min: res.voice_config.speed.min,
          step: res.voice_config.speed.separate,
          default: res.voice_config.speed.default,
        };
        state.voiceConfige.emotion_intensity = {
          max: res.voice_config.intensity.max,
          min: res.voice_config.intensity.min,
          step: res.voice_config.intensity.separate,
        };
        state.voiceConfige.volume = {
          max: res.voice_config.volume.max,
          min: res.voice_config.volume.min,
          step: res.voice_config.volume.separate,
        };

        // 存储 推荐专属的声音配置
        state.volcengine_config.speed = {
          max: res.volcengine_config.speed.max,
          min: res.volcengine_config.speed.min,
          step: res.volcengine_config.speed.separate,
          default: res.volcengine_config.speed.default,
        };

        // 储存 克隆专属的语速配置
        state.speed_ratio.speed = {
          max: res.volcengine_clone_config.speed.max,
          min: res.volcengine_clone_config.speed.min,
          step: res.volcengine_clone_config.speed.separate,
          default: res.volcengine_clone_config.speed.default,
        };
      }
    };

    const changeFn = () => {
        state.isExpanded = !state.isExpanded;
    }

    const initRule = async() => {
      const res = await request.get(
      "/work_ai",
      "/user/shotstack/point/story/get",
      {
        number: "1",
      }
      );
      state.unit = res.pointInfo.unit
      state.unit_name = res.pointInfo.name

      state.consumes = res.pointInfo.consumes
    }


    initRule()


    const Text_story_Change = async () => {
      if (state.Text_activeKey == "2") {
        state.textList.forEach((item, index) => {
          if (item.isResultUrl) {
            // item.playNum = 1
            item.isPlay = true
          }
        })
        
      } else {
        state.storyList.forEach((item, index) => {
          if (item.isResultUrl) {
            // item.playNum = 1
            item.isPlay = true
          }
        })
     
      }
    
      nextTick(()=>{
     
      })
    }

    // 获取富文本内容, 并将state.text 同步的方法
    const synchronizeText = (index) => {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          const editorData = editorRef.value[index]?.getContent()
          resolve(editorData)
        }, 500);
      })
    }

    const handleScroll = () => {
      if (state.voiceListContainer) {
        const scrollTop = state.voiceListContainer.scrollTop;
        const scrollHeight = state.voiceListContainer.scrollHeight;
        const clientHeight = state.voiceListContainer.clientHeight;

        // console.log(scrollTop,  'scrollTopscrollTopscrollTop');
        console.log(scrollHeight,  'scrollHeightscrollHeightscrollHeight');
        console.log(clientHeight, 'clientHeightclientHeightclientHeightclientHeight');

        const flage = (clientHeight >= scrollHeight - 5)

        console.log('出不出滚动条');
        state.ismore =  flage; // 这里的5是容差值
        // console.log(state.ismore,   'dwdwdw');

      }
    };

    // watch(() => state.voiceListContainer, (nv, ov) => {
    //   nv && handleScroll()
    // }, {
    //   deep:true
    // })


    

    return {
      ...toRefs(state),
      addTxt,
      max_text_length,
      vipVisible,
      Empty,
      vipModalRef,
      delTxt,
      playbackClick,
      activeChange,
      voiceClick,
      playAutoClick,
      indicator,
      handleOk,
      textareaChange,
      downloadSound,
      saveMaterials,
      audioStatus,
      setAudio,
      currentImportIndex,
      copyLibraryModal,
      openCopyLibraryModal,
      audioLItemImportSuccess,
      notVoiceNumDialogRef,
      changeFn,
      initRule,
      Text_story_Change,
      handleScroll,
      aIRewriting,
      editorRef,
    };
  },
  
});
</script>

<style lang="less" scoped>
.smart-clip {
  padding: 24px 24px 0;
}

button {
  border-radius: 5px;
}

:deep(.ss-select-selector) {
  border-radius: 0 5px 5px 0 !important;
}

.dubbing {
  display: flex;
}

.copywriting {
  // display: flex;
  margin-bottom: 20px;
}

.copywriting-content {
  display: flex;
}

.copywriting-music {
  .copywritingmusic-title {
    width: 100%;
    padding: 12px 0;
    display: flex;
    .left {
      display: flex;
    }
  }
}

.voice_type_box{
  width: calc(100% - 80px);

  .voice_type_list{
    max-height: 200px;
    overflow-y: auto;

    &::-webkit-scrollbar {
          width: 6px; /* 滚动条的宽度 */
          height: 10px; /* 滚动条的高度，垂直滚动条可能用得上 */
      }
      &::-webkit-scrollbar-thumb {
          background: #dfdfdf; /* 滑块的背景颜色 */
          border-radius: 10px; /* 滑块的圆角 */
      }
  }
}

.dubbing-title,
.copywriting-title {
  display: flex;
  justify-content: flex-end;
  margin-right: 5px;
  padding: 12px 0;
}

.ss-card {
  border-radius: 10px;
  margin: 20px 0;
}

.n-tab-pane {
  display: flex;

  .group-box {
    display: flex;
    align-items: center;
    width: 150px;
    height: 68px;
    padding: 0px 10px;
    margin-bottom: 20px;
    margin-right: 20px;
    border-radius: 5px;
    border: 1px solid #d9d9d9;
    cursor: pointer;
    position: relative;

    &.group-border {
      border: 1px solid #436ba0;
    }

    .avatar {
      position: relative;
      margin-right: 5px;
    }

    .spain_spain {
      position: absolute;
      display: flex;
      justify-content: center;
      align-items: center;
      left: 0px;
      top: 1px;
      width: 32px;
      height: 32px;
      border-radius: 50%;
      background: rgba(0, 0, 0, 0.3);
    }

    .mask {
      position: absolute;
      top: 0px;
      left: 1px;
      width: 32px;
      height: 32px;
      border-radius: 50%;
      background: rgba(0, 0, 0, 0.3);

      .icon {
        margin-left: 8px;
        margin-top: 6px;
        color: #fff;
        font-size: 18px;
      }

      display: none;
    }

    :hover {
      .mask {
        display: block;
      }
    }

    .right-badge {
      position: absolute;
      top: 0;
      right: 0;
      width: auto;
      height: 20px;
      padding: 5px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #fff;
      font-size: 12px;
      border-radius: 2px;
      background: #ff9c00;
    }
  }
}

.group-title {
  width: 90px;
  // display: flex;
  // justify-content: center;
}

.role_box {
  width: calc(100% - 100px);
  display: flex;
  flex-wrap: wrap;
}

.role_item {
  flex: 0 0 25%;
  height: 40px;
}

:deep(.ss-radio-wrapper) {
  margin-right: 0px;
}

.ss-radio-group {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
}

.group-name {
  width: 80px;
}

.voice {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.voice-item {
  display: flex;
  align-items: center;
}

.ss-slider {
  width: 160px;
}

.textarea-wrapper {
  width: 100%;
  position: relative;
  border: 1px solid #eaeaea;
  padding: 20px 20px 45px 20px;
  position: relative;

  .import_meatiner_btn {
    display: block;
  }

  // &:hover .import_meatiner_btn {
  //   display: block;
  // }

  .mask-text {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(255, 255, 255, 0.5);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    .mask-box {
      width: 176px;
      height: 62px;
      color: #2878ff;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }

  :deep(.editor_component .content .ProseMirror) {
    background: #f6f6f6;
  }
  :deep(.editor_component){
    height: 420px;
  }
}

.operation {
  display: flex;
  align-items: center;
  justify-content: space-between;
  // height: 60px;
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  padding: 10px;

  .auto-box {
    margin-right: 10px;
  }
}

.operation-btn {
  font-size: 24px;
  color: #666;
  margin-left: 10px;
  cursor: pointer;
}

.add-btn {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
  // margin-left: 95px;
}


.see_more {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #686e7b;
  cursor: pointer;
  margin-top: 10px;
}

.expanded {
    max-height: 100% !important;
    // max-height: 446px !important;
     overflow-y: auto;
}
</style>
